package com.taotao.content.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.EasyUITreeNode;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.content.service.ContentCategoryService;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.pojo.TbContentCategoryExample.Criteria;
/**
 * 内容分类
 * @title ContentCategoryImpl
 * <p>description</p>
 * <p>company: www.itheima.com</p>
 * @author 天火
 * @version 1.0
 */
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {

	@Autowired
	private TbContentCategoryMapper ccMapper;	
	
	@Override
	public List<EasyUITreeNode> getContentCategoryList(Long parentId) {
		// 1.注入mapper
		//2.创建exampler
		TbContentCategoryExample tExample = new TbContentCategoryExample();
		//3.设置条件
		Criteria criteria = tExample.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		
		//4.创建查询
		List<TbContentCategory> list = ccMapper.selectByExample(tExample);
		//5.转成EasyUITreeNode列表
		List<EasyUITreeNode> node = new ArrayList<>();
		for(TbContentCategory tbContentCategory : list) {
			EasyUITreeNode eNode = new EasyUITreeNode();
			eNode.setId(tbContentCategory.getId());
			eNode.setState(tbContentCategory.getIsParent()?"closed":"open");
			eNode.setText(tbContentCategory.getName());
			node.add(eNode);
		}
		///6.返回
		
		return node;
	}

	@Override
	public TaotaoResult createContentCategory(long parentId, String name) {
		//1. 构建一个对象
		TbContentCategory tCategory  = new TbContentCategory();
		tCategory.setCreated(new Date());
		tCategory.setIsParent(false);
		tCategory.setName(name);
		tCategory.setParentId(parentId);
		tCategory.setSortOrder(1);
		tCategory.setStatus(1);
		tCategory.setUpdated(tCategory.getCreated());
		//2. 插入contentcatgory数据
		ccMapper.insertSelective(tCategory);
		//3. 返回taotaoResult 包含内容的id 需要主键返回
		
		//判断添加本省的节点是叶子节点没要将其改为父节点
		TbContentCategory paCategory = ccMapper.selectByPrimaryKey(parentId);
		if(paCategory.getIsParent()==false) {
			paCategory.setIsParent(true);
			ccMapper.updateByPrimaryKeySelective(paCategory);
		}
		
		
		return TaotaoResult.ok(tCategory);
	}

}
